// 处理画布数据的序列化和反序列化
const handleCanvasData = (e) => {
    const { type, data, messageId } = e.data;

    if (type === 'serialize') {
        try {
            // 序列化画布数据
            const serialized = JSON.stringify(data, (key, value) => {
                // 处理特殊对象
                if (value instanceof Object && value.type) {
                    return {
                        ...value,
                        _serialized: true
                    };
                }
                return value;
            });

            self.postMessage({
                type: 'serialized',
                data: serialized,
                success: true,
                messageId
            });
        } catch (error) {
            console.error('序列化失败:', error);
            self.postMessage({
                type: 'serialized',
                error: error.message,
                success: false,
                messageId
            });
        }
    } else if (type === 'deserialize') {
        try {
            // 反序列化画布数据
            const deserialized = JSON.parse(data, (key, value) => {
                // 处理特殊对象
                if (value && value._serialized) {
                    delete value._serialized;
                    return value;
                }
                return value;
            });

            self.postMessage({
                type: 'deserialized',
                data: deserialized,
                success: true,
                messageId
            });
        } catch (error) {
            console.error('反序列化失败:', error);
            self.postMessage({
                type: 'deserialized',
                error: error.message,
                success: false,
                messageId
            });
        }
    }
};

self.addEventListener('message', handleCanvasData);